package day04

import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
  * 需求：记录上一个批次的历史数据
  *
  */
object RecordHistoryValue {
  def updateFunc(currentValue:Seq[Int],historyValue: Option[Int]):Option[Int]={
    val result=currentValue.sum+historyValue.getOrElse(0)
    Some(result)
  }
  def main(args: Array[String]): Unit = {
    val sparkConf: SparkConf = new SparkConf().setAppName("AcceptScoketData").setMaster("local[2]")
    val sc: SparkContext = new SparkContext(sparkConf)
    sc.setLogLevel("WARN")
    val ssc: StreamingContext = new StreamingContext(sc,Seconds(5))
    //设置chkpoint目录
    ssc.checkpoint("./streaming-chk")
    //接收scoket数据
    val data: ReceiverInputDStream[String] = ssc.socketTextStream("node01",9999)
    //进行单词计数
    val wordAnd1: DStream[(String, Int)] = data.flatMap(x=>x.split(" ")).map((_,1))
    val result: DStream[(String, Int)] = wordAnd1.updateStateByKey(updateFunc)
    result.print()
    //开启流式计算
    ssc.start()
    ssc.awaitTermination()
  }
}
